package com.lon.over.ui.fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.lon.over.R;
import com.lon.over.base.BaseFragment;
import com.lon.over.model.domain.Categories;
import com.lon.over.presenter.IHomePresenter;
import com.lon.over.presenter.impl.HomePresenterImpl;
import com.lon.over.ui.adapter.HomePagerAdapter;
import com.lon.over.view.IHomeCallback;

import butterknife.BindView;

/**
 * author: ctl
 * 创建时间: 2022/4/22
 * Describe:
 */
public class HomeFragment extends BaseFragment implements IHomeCallback {

    @BindView(R.id.home_indicator)
    public TabLayout mTabLayout;

    @BindView(R.id.home_page)
    public ViewPager homePager;

    private IHomePresenter mHomePresenter;

    private HomePagerAdapter mHomePagerAdapter;

    /**
     * 加载界面ID 要显示的界面
     */
    @Override
    protected int getRootViewId() {
        return R.layout.fragment_home;
    }


    /**
     * 初始化组件
     *
     * @param rootView
     */
    @Override
    protected void initView(View rootView) {
        //初始化控件
        mTabLayout.setupWithViewPager(homePager);
        //给ViewPager设置适配器
        mHomePagerAdapter = new HomePagerAdapter(getChildFragmentManager());
        // 设置适配器
        homePager.setAdapter(mHomePagerAdapter);
    }

    /**
     * 复写Fragment，将顶部导航栏独立出来
     *
     * @param inflater
     * @param container
     * @return
     */
    @Override
    protected View loadRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.base_home_fragment_layout, container, false);
    }

    /**
     * 加载逻辑层 | 加载Presenter
     */
    @Override
    protected void initPresenter() {
        mHomePresenter = new HomePresenterImpl();
        mHomePresenter.registerViewCallback(this);
    }

    /**
     * 加载数据
     */
    @Override
    public void loadData() {
        if (mHomePresenter != null) {
            mHomePresenter.getCategories();
        }
    }

    /**
     * 加载的数据就会从这里回来
     *
     * @param categories
     */
    @Override
    public void onCategoriesLoad(Categories categories) {
        setUpState(State.SUCCESS);
        if (categories != null) {
            mHomePagerAdapter.setCategories(categories);
        }
    }

    /**
     * 复写点击重试，当网络出现问题时，点击刷新
     */
    @Override
    protected void onRetryClick() {
        if (mHomePresenter != null) {
            mHomePresenter.getCategories();
        }
    }

    /**
     * 取消回调注册
     */
    @Override
    protected void release() {
        if (mHomePresenter != null) {
            mHomePresenter.unregisterViewCallback(this);
        }
    }


    @Override
    public void onError() {
        setUpState(State.ERROR);
    }

    @Override
    public void onLading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }
}
